﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RATSharp.Rest;
using RATSharp.Model;
using RATSharp.Collection;
using RATSharp;
using RATSharp.Validator;

namespace RATSharp.Cal
{
    /// <summary>
    /// Represents Return It Back submenu
    /// </summary>
    public class ReturnItBackAction
    {
        private RestService service;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="service">rest service</param>
        public ReturnItBackAction(RestService service)
        {
            this.service = service;
        }

        /// <summary>
        /// show all available non-returned items 
        /// </summary>
        public void returnItBack()
        {
            bool stepback = false;
            while (!stepback)
            {

                Reservations responseRes;
                if (!MenuUtilities.WaitForCommTask(service.getAllUnreturnedItems(), out responseRes))
                {
                    return;
                }

                if (responseRes == null || responseRes.Count == 0)
                {
                    Console.WriteLine("No unreturned objects has been found");
                    return;
                }

                MenuUtilities.MakeBidirectionalConnection(responseRes);

                MenuList<MenuItem<Period, CalendarPeriodHandler>, MenuItem<string, CalendarPeriodHandler>> periodList =
                  new MenuList<MenuItem<Period, CalendarPeriodHandler>, MenuItem<string, CalendarPeriodHandler>>("Unreturned reservations");

                foreach (Reservation res in responseRes)
                {
                    foreach (Period per in res.periods)
                    {
                        periodList.Add(new MenuItem<Period, CalendarPeriodHandler>(per, new CalendarPeriodHandler(returnPeriod)));
                    }
                }

                periodList.AddAdditional(new MenuItem<string, CalendarPeriodHandler>("Step Back", delegate(Period delPer) { stepback = true; }));


                Console.Write(periodList);

                int choice = MenuUtilities.GetSimpleInput(new IntRangeInputValidator(1, periodList.fullCount)) - 1;

                if (choice < periodList.Count)
                {
                    periodList.ElementAt(choice).menuHandler(periodList.ElementAt(choice).value);
                }
                else
                {
                    periodList.GetAdditional(choice).menuHandler(null);
                }

            }
        }


        private void returnPeriod(Period period)
        {
            Reservations res;
            if (!MenuUtilities.WaitForCommTask(service.returnItem(period.id), out res))
            {
                return;
            }
            Console.WriteLine("Object has been returned!");

        }
    }
}
